//
//  PreLoginViewController2.m
//  safeLady
//
//  Created by Justsoso on 2017/6/19.
//  Copyright © 2017年 xmy. All rights reserved.
//

#import "PreLoginViewController2.h"
#import "PreLoginViewModel.h"


CGFloat const leftPadding = 60.0f;              // 左边间距
CGFloat const topPadding = 25.0f;               // 上下间距

CGFloat const labelHeight = 30.0f;              // 标题文字的高度
CGFloat const labelAnimationDuration = 0.3;     // 标题的动画时间
CGFloat const labelScaling = 0.8;               // 标题的缩放比例

CGFloat const lineWidth = 2.0f;                 // 线的宽度
CGFloat const lineNormalControlY = 0;           // 线的默认控制点
CGFloat const lineAnimationControlY1 = 60;      // 线的动画控制点1
CGFloat const lineAnimationControlY2 = -40;     // 线的动画控制点2
CGFloat const lineAnimationDuration1 = 0.15;    // 线的动画时间1
CGFloat const lineAnimationDuration2 = 0.1;     // 线的动画时间2
CGFloat const lineAnimationDuration3 = 0.095;   // 线的动画时间3
CGFloat const lineAnimationDuration4 = 0.5;     // 半圆线的动画时间

CGFloat const textFieldHeight = 30.0f;          // 输入框高度

CGFloat const buttonHeight = 30.0f;             // 登录按钮高度

CGFloat const normalAnimationDuration = 0.3;    // 默认动画时间


@interface PreLoginViewController2 ()<CAAnimationDelegate, UITextFieldDelegate> 

@property (nonatomic, strong) UILabel *telePhoneLabel;         // 手机号标题
@property (nonatomic, strong) UILabel *codeLabel;              // 验证码标题
@property (nonatomic, strong) UILabel *shuLabel;               // 竖线

@property (nonatomic, strong) CAShapeLayer *telePhoneLine;     // 手机号线
@property (nonatomic, strong) CAShapeLayer *codeLine;          // 验证码线
@property (nonatomic, strong) CAShapeLayer *arcLine;           // 半圆线

@property (nonatomic, strong) UITextField *telePhoneTextField; // 手机号输入框
@property (nonatomic, strong) UITextField *codeTextField;      // 验证码输入框

@property (nonatomic, strong) UIButton *loginButton;           // 登录按钮
@property (nonatomic, strong) UIButton *getCodeButton;         // 获取验证码
@property (nonatomic, strong) UIButton *userAgreement;         // 用户协议
@property (nonatomic, strong) UIButton *tickButton;            // 勾

@property (nonatomic, assign) BOOL telePhoneIsEdit;            // 用手机号正在编辑
@property (nonatomic, assign) BOOL codeIsEdit;                 // 验证码正在编辑
@property (nonatomic, strong) NSNumber *isTick;                     // 是否选中

@property (nonatomic, assign) NSInteger animationTime1;        // 动画次数
@property (nonatomic, assign) NSInteger animationTime2;        // 动画次数

@property (nonatomic, strong) PreLoginViewModel *viewModel;    // 登录模型


@end

@implementation PreLoginViewController2
@synthesize viewModel = _viewModel;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.navigationController.navigationBar setHidden:YES];
    
    
    /* 初始化视图 */
    [self initViews];
    
    /* 增加监听（当键盘出现或改变时） */
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    
    /* 增加监听（当键盘退出时） */
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
}

/**
 初始化视图
 */
- (void)initViews {
    
    CGFloat width = self.view.frame.size.width - leftPadding * 2;   // 控件宽度
    UIFont *labelFont = [UIFont systemFontOfSize:17.0f];            // 标题文字大小
    UIFont *textFieldFont = [UIFont systemFontOfSize:14.0f];        // 输入框文字大小
    UIFont *buttonFont = [UIFont systemFontOfSize:15.0f];           // 登录按钮文字大小

    
    /* 用户名标题 */
    CGFloat usernameLabelY = self.view.center.y - 100;
    self.telePhoneLabel = [[UILabel alloc] initWithFrame:CGRectMake(leftPadding, usernameLabelY, width - (width / 2.5), labelHeight)];
    self.telePhoneLabel.text = @"请输入手机号";
    self.telePhoneLabel.textColor = [UIColor colorWithHex:0x99999];
    self.telePhoneLabel.font = labelFont;
    self.telePhoneLabel.userInteractionEnabled = YES;
    [self.view addSubview:self.telePhoneLabel];
    
    /* 添加用户名点击事件 */
    UITapGestureRecognizer *telePhoneTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(telePhoneTapDo)];
    [self.telePhoneLabel addGestureRecognizer:telePhoneTap];
    
    /* 用户名线 */
    CGFloat usernameLineY = usernameLabelY + labelHeight;
    self.telePhoneLine = [CAShapeLayer layer];
    self.telePhoneLine.frame = CGRectMake(leftPadding, usernameLineY, width, 0);
    self.telePhoneLine.lineWidth = lineWidth;                       // 线宽
    self.telePhoneLine.strokeColor = [UIColor whiteColor].CGColor;  // 线的颜色
    self.telePhoneLine.fillColor = [UIColor clearColor].CGColor;    // 填充色
//    self.telePhoneLine.path = [self getBezierPath:lineNormalControlY];
    self.telePhoneLine.path = [self getBezierLine1:self.codeTextField.frame.size.width];
    
    [self.view.layer addSublayer:self.telePhoneLine];
    
    /* 用户名输入框 */
    CGFloat usernameTextFieldY = usernameLineY - textFieldHeight;
    self.telePhoneTextField = [[UITextField alloc] initWithFrame:CGRectMake(leftPadding, usernameTextFieldY, width - (width / 2.5), textFieldHeight)];
    self.telePhoneTextField.maxLenght = 11;
    self.telePhoneTextField.textColor = [UIColor whiteColor];
    self.telePhoneTextField.font = textFieldFont;
//    self.telePhoneTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.telePhoneTextField.enabled = NO;
    self.telePhoneTextField.delegate = self;
    self.telePhoneTextField.keyboardType = UIKeyboardTypeNumberPad;
    
    [self.view addSubview:self.telePhoneTextField];
    
    /* 验证码标题 */
    CGFloat passwordLabelY = usernameLineY + topPadding;
    self.codeLabel = [[UILabel alloc] initWithFrame:CGRectMake(leftPadding, passwordLabelY, width, labelHeight)];
    self.codeLabel.text = @"请输入验证码";
    self.codeLabel.textColor = [UIColor colorWithHex:0x99999];
    self.codeLabel.font = labelFont;
    self.codeLabel.userInteractionEnabled = YES;
    [self.view addSubview:self.codeLabel];
    
    /* 添加验证码点击事件 */
    UITapGestureRecognizer *codeTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(codeTapDo)];
    [self.codeLabel addGestureRecognizer:codeTap];
    
    /* 验证码线 */
    CGFloat passwordLineY = passwordLabelY + labelHeight;
    self.codeLine = [CAShapeLayer layer];
    self.codeLine.frame = CGRectMake(leftPadding, passwordLineY, width, 0);
    self.codeLine.lineWidth = lineWidth;                            // 线宽
    self.codeLine.strokeColor = [UIColor whiteColor].CGColor;       // 线的颜色
    self.codeLine.fillColor = [UIColor clearColor].CGColor;         // 填充色
//    self.codeLine.path = [self getBezierPath:lineNormalControlY];
    self.codeLine.path = [self getBezierLine1:self.codeTextField.frame.size.width];
    [self.view.layer addSublayer:self.codeLine];
    
    /* 验证码输入框 */
    CGFloat passwordTextFieldY = passwordLineY - textFieldHeight;
    self.codeTextField = [[UITextField alloc] initWithFrame:CGRectMake(leftPadding, passwordTextFieldY, width, textFieldHeight)];
    self.codeTextField.textColor = [UIColor whiteColor];
    self.codeTextField.maxLenght = 4;
    self.codeTextField.font = textFieldFont;
//    self.codeTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.codeTextField.enabled = NO;
    self.codeTextField.delegate = self;
    self.codeTextField.keyboardType = UIKeyboardTypeNumberPad;
    
    [self.view addSubview:self.codeTextField];
    
    
    /* 登录按钮 */
    self.loginButton = [[UIButton alloc] init];
    self.loginButton.titleLabel.font = buttonFont;
    [self.loginButton setTitle:@"立即进入" forState:UIControlStateNormal];
//    [self.loginButton setTitleColor:[UIColor clearColor] forState:UIControlStateNormal];
//    [self.loginButton setBackgroundColor:[UIColor clearColor]];
    [self.loginButton.layer setBorderColor:[UIColor whiteColor].CGColor];
    [self.loginButton.layer setBorderWidth:1];
    [self.loginButton.layer setCornerRadius:15];
    [self.loginButton.layer setMasksToBounds:YES];
    [self.view addSubview:self.loginButton];
    [self.loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.codeTextField.mas_bottom).offset(40);
        make.centerX.equalTo(self.view);
        make.height.equalTo(@(buttonHeight));
        make.width.equalTo(@(width / 1.5));
    }];
    
    
    /* 发送验证码按钮 */
    self.getCodeButton = [[UIButton alloc] init];
    [self.getCodeButton setTitle:@"发送验证码" forState:UIControlStateNormal];
    [self.getCodeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.getCodeButton.titleLabel.font = buttonFont;
    [self.getCodeButton setBackgroundColor:[UIColor clearColor]];
    self.getCodeButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [self.getCodeButton addTarget:self action:@selector(getCodeContent) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.getCodeButton];
    [self.getCodeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.telePhoneTextField);
        make.right.equalTo(self.codeTextField.mas_right);
        make.width.equalTo(@(width / 2.5));
        make.height.equalTo(@(self.telePhoneTextField.height));
        
    }];
    
    /* 手机号与发送验证码中间的竖线 */
    self.shuLabel = [[UILabel alloc] init];
    self.shuLabel.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.shuLabel];
    [self.shuLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.getCodeButton);
        make.width.equalTo(@1);
        make.left.equalTo(self.getCodeButton.mas_left).offset(-5);
        make.height.equalTo(@(buttonHeight / 2));
    }];
    
    /* 半圆的线 */
    self.arcLine = [CAShapeLayer layer];
    self.arcLine.lineWidth = 2.0f;
    self.arcLine.strokeColor = [UIColor whiteColor].CGColor;
    self.arcLine.fillColor = [UIColor clearColor].CGColor;
    self.arcLine.path = [self getBezierLine2];
    
    self.arcLine.strokeStart = 0;
    self.arcLine.strokeEnd = 0;
    
    [self.view.layer addSublayer:self.arcLine];
    
    /* 用户协议Label */
    self.userAgreement = [[UIButton alloc] init];
    [self.userAgreement setTitle:@"查看用户隐私协议" forState:UIControlStateNormal];
    [self.userAgreement setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.userAgreement setBackgroundColor:[UIColor clearColor]];
    self.userAgreement.titleLabel.font = [UIFont systemFontOfSize:10.0f];
    
//    [self.userAgreement addTarget:self action:@selector(lookUserAgreement) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:self.userAgreement];
    
    /* 宽度自适应 */
    [self.userAgreement setContentCompressionResistancePriority:UILayoutPriorityRequired
                                             forAxis:UILayoutConstraintAxisHorizontal];
    [self.userAgreement setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
    
    [self.userAgreement mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.loginButton.mas_centerX);
        make.height.equalTo(@20);
        make.bottom.equalTo(self.view.mas_bottom).offset(-20);
    }];
    
//    /* 勾 */
//    self.tickButton = [[UIButton alloc] init];
//    [self.tickButton setBackgroundImage:[UIImage imageNamed:@"勾"] forState:UIControlStateNormal];
//    [self.tickButton setBackgroundColor:[UIColor clearColor]];
//    self.isTick = @1;
//    
//    [self.tickButton addTarget:self action:@selector(selectorUserAgreement) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:self.tickButton];
//    [self.tickButton mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.right.equalTo(self.userAgreement.mas_left).offset(-5);
//        make.centerY.equalTo(self.userAgreement.mas_centerY);
//        make.width.height.equalTo(@10);
//    }];
    
    
}

- (void)selectorUserAgreement {
//    if (self.isTick == YES) {
//        self.isTick = NO;
//        [self.tickButton setBackgroundImage:[UIImage imageNamed:@"框"] forState:UIControlStateNormal];
//    }else if (self.isTick == NO) {
//        self.isTick = YES;
//        [self.tickButton setBackgroundImage:[UIImage imageNamed:@"勾"] forState:UIControlStateNormal];
//    }
    
//    self.isTick = [self.isTick isEqualToNumber:@1] ? @0 : @1;
//    self.viewModel.isTick = self.isTick;
//    [self.tickButton setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@",[self.isTick isEqualToNumber:@1] ? @"勾" : @"框"]] forState:UIControlStateNormal];
    
}


/**
 用户协议点击事件
 */
//- (void)lookUserAgreement {
//    UIStoryboard *story = [UIStoryboard storyboardWithName:@"LoginTo" bundle:[NSBundle mainBundle]];
//    UIViewController *userAgreementVC = [story instantiateViewControllerWithIdentifier:@"UserAgreementViewController"];
//    [self.navigationController pushViewController:userAgreementVC animated:YES];
    
//    UserAgreementViewController *userAgreement = [[UserAgreementViewController alloc] init];
//    [self.navigationController pushViewController:userAgreement animated:YES];
//}



/**
 手机号点击事件
 */
- (void)telePhoneTapDo {
    
    self.telePhoneIsEdit = YES;
    self.codeIsEdit = NO;
    self.telePhoneLine.path = [self getBezierPath:lineNormalControlY];
    [self startLineAnimation];
}


/**
 密码点击事件
 */
- (void)codeTapDo {
    
    self.telePhoneIsEdit = NO;
    self.codeIsEdit = YES;
    self.codeLine.path = [self getBezierPath:lineNormalControlY];
    [self startLineAnimation];
}


/**
 发送验证码点击时间
 */
- (void)getCodeContent {
    
//    self.codeLine.path = [self getBezierLine1:self.codeTextField.frame.size.width];
//    [self startLineAnimation2];
    
}


/**
 获取贝塞尔曲线路径
 
 @param controlY 控制点的 Y 值
 @return 曲线路径
 */
- (CGPathRef)getBezierPath:(CGFloat)controlY {
    
    CGFloat width = self.view.frame.size.width - leftPadding * 2;
    
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(0, 0)]; // 设置起点
    [path addQuadCurveToPoint:CGPointMake(width, 0) controlPoint:CGPointMake(width / 2, controlY)]; // 设置终点和控制点
    return path.CGPath;
}


/**
 手机号线消失的路径
 
 @param width 传入的起点Y
 @return 路径
 */
- (CGPathRef)getBezierLine1:(CGFloat)width {
    
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(width, 0)];
    [path addQuadCurveToPoint:CGPointMake(self.codeTextField.frame.size.width, 0) controlPoint:CGPointMake(self.codeTextField.frame.size.width, 0)];
    return path.CGPath;
}



/**
 验证码线出现和消失的路径
 
 @param width 传入的终点和控制点
 @return 路径
 */
- (CGPathRef)getBezierLine4:(CGFloat)width {
    
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(0, 0)];
    [path addQuadCurveToPoint:CGPointMake(width, 0) controlPoint:CGPointMake(width, 0)];
    return path.CGPath;
}


/**
 出现的半圆路径
 
 @return 路径
 */
- (CGPathRef)getBezierLine2 {
    
    CGFloat radius = (self.codeLine.frame.origin.y - self.telePhoneLine.frame.origin.y) / 2; // 半圆半径
    CGFloat arcX = self.telePhoneLine.frame.origin.x + self.telePhoneLine.frame.size.width;  // 半圆原点X值
    CGFloat arcY = self.telePhoneLine.frame.origin.y + radius;                               // 半圆原点Y值
    
    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(arcX, arcY) radius:radius startAngle:(1.5 * M_PI) endAngle:(0.5 * M_PI) clockwise:YES];
    
    return path.CGPath;
}


/**
 消失的半圆的路径
 
 @return 路径
 */
- (CGPathRef)getBezierLine3 {
    
    CGFloat radius = (self.codeLine.frame.origin.y - self.telePhoneLine.frame.origin.y) / 2; // 半圆半径
    CGFloat arcX = self.telePhoneLine.frame.origin.x + self.telePhoneLine.frame.size.width;  // 半圆原点X值
    CGFloat arcY = self.telePhoneLine.frame.origin.y + radius;                               // 半圆原点Y值
    
    
    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(arcX, arcY) radius:radius startAngle:(0.5 * M_PI) endAngle:(1.5 * M_PI) clockwise:NO];
    
    
    return path.CGPath;
    
}


/**
 开始线的动画效果
 */
- (void)startLineAnimation {
    
    CAShapeLayer *lineLayer = self.telePhoneIsEdit? self.telePhoneLine : self.codeLine;
    
    /* 第一段动画 */
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"path"];
    animation.delegate = self;
    animation.duration = lineAnimationDuration1;
    animation.fromValue = (__bridge id _Nullable)([self getBezierPath:lineNormalControlY]);
    animation.toValue = (__bridge id _Nullable)([self getBezierPath:lineAnimationControlY1]);
    [lineLayer addAnimation:animation forKey:@"PathAnimation"];
    self.animationTime1 ++;
}


/**
 点击发送验证开始的动画
 */
- (void)startLineAnimation2 {
    
    /* 手机号线开始消失 */
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"path"];
    animation.delegate = self;
    animation.duration = lineAnimationDuration4;
    animation.fromValue = (__bridge id _Nullable)([self getBezierLine1:0]);
    animation.toValue = (__bridge id _Nullable)([self getBezierLine1:self.codeTextField.frame.size.width]);
    self.telePhoneLine.path = [self getBezierLine1:self.codeTextField.frame.size.width];
    [self.telePhoneLine addAnimation:animation forKey:@"PathAnimation"];
    
    /* 半圆动画开始出现 */
    animation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    
    animation.fromValue = [NSNumber numberWithFloat:0];
    animation.toValue = [NSNumber numberWithFloat:1];
    
    CAAnimationGroup *strokeAnimationGroup = [CAAnimationGroup animation];
    strokeAnimationGroup.duration = lineAnimationDuration4;
    strokeAnimationGroup.animations = @[animation];
    self.arcLine.path = [self getBezierLine2];
    [self.arcLine addAnimation:strokeAnimationGroup forKey:nil];
    
    self.animationTime2++;
}

/**
 线的动画执行结束（代理方法）
 
 @param anim 动画对象
 @param flag 状态
 */
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    
    CAShapeLayer *lineLayer = self.telePhoneIsEdit ? self.telePhoneLine : self.codeLine;
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"path"];
    animation.delegate = self;
    
    /* 第二段动画 */
    if (self.animationTime1 == 1) {
        
        animation.duration = lineAnimationDuration2;
        animation.fromValue = (__bridge id _Nullable)([self getBezierPath:lineAnimationControlY1]);
        animation.toValue = (__bridge id _Nullable)([self getBezierPath:lineAnimationControlY2]);
        [lineLayer addAnimation:animation forKey:@"PathAnimation"];
        self.animationTime1 ++;
        
        [self startLabelAnimation:YES]; // 开始标题缩小的动画效果
    }
    /* 第三段动画 */
    else if (self.animationTime1 == 2) {
        
        animation.duration = lineAnimationDuration3;
        animation.fromValue = (__bridge id _Nullable)([self getBezierPath:lineAnimationControlY2]);
        animation.toValue = (__bridge id _Nullable)([self getBezierPath:lineNormalControlY]);
        [lineLayer addAnimation:animation forKey:@"PathAnimation"];
        self.animationTime1 = 0;
    }
    if (self.animationTime2 == 1) {

        /* 密码线开始出现 */
        animation.duration = lineAnimationDuration4;
        animation.fromValue = (__bridge id _Nullable)([self getBezierLine1:self.codeTextField.frame.size.width]);
        animation.toValue = (__bridge id _Nullable)([self getBezierLine1:0]);
        self.codeLine.path = [self getBezierLine1:0];
        [self.codeLine addAnimation:animation forKey:@"PathAnimation"];
        
        /* 半圆动画开始消失 */
        animation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
        animation.fromValue = [NSNumber numberWithFloat:1];
        animation.toValue = [NSNumber numberWithFloat:0];
        CAAnimationGroup *strokeAnimationGroup = [CAAnimationGroup animation];
        strokeAnimationGroup.duration = lineAnimationDuration4;
        strokeAnimationGroup.animations = @[animation];
        self.arcLine.path = [self getBezierLine3];
        [self.arcLine addAnimation:strokeAnimationGroup forKey:nil];
        
        self.animationTime2 = 0;

    }
}


/**
 开始标题缩放的动画效果
 
 @param isShrink 是否缩小
 */
- (void)startLabelAnimation:(BOOL)isShrink {
    
    UILabel *label = self.telePhoneIsEdit ? self.telePhoneLabel : self.codeLabel;
    UITextField *textField = self.telePhoneIsEdit ? self.telePhoneTextField : self.codeTextField;
    [self setAnchorPoint:CGPointMake(0, 0) forView:label]; // 设置缩放围绕的点
    [UIView animateWithDuration:labelAnimationDuration animations:^{
        
        CGFloat scaling = isShrink? labelScaling : 1; // 缩放比例
        label.transform = CGAffineTransformMakeScale(scaling, scaling);
        
        CGFloat padding = isShrink? -15 : 15; // 偏移距离
        CGRect frame =  label.frame;
        frame.origin.y += padding;
        label.frame = frame;
        
    } completion:^(BOOL finished) {
        
        label.userInteractionEnabled = !isShrink;
        textField.enabled = isShrink;
        if (isShrink) {
            
            [textField becomeFirstResponder];
        }
    }];
}


/**
 设置缩放围绕的特定点
 
 @param anchorPoint 围绕的点
 @param view 设置的视图
 */
- (void)setAnchorPoint:(CGPoint)anchorPoint forView:(UIView *)view {
    
    CGPoint oldOrigin = view.frame.origin;
    view.layer.anchorPoint = anchorPoint;
    CGPoint newOrigin = view.frame.origin;
    
    CGPoint transition;
    transition.x = newOrigin.x - oldOrigin.x;
    transition.y = newOrigin.y - oldOrigin.y;
    
    view.center = CGPointMake (view.center.x - transition.x, view.center.y - transition.y);
}


/**
 将缩放围绕的特定点还原为默认
 
 @param view 设置的视图
 */
- (void)setDefaultAnchorPointforView:(UIView *)view {
    
    [self setAnchorPoint:CGPointMake(0.5f, 0.5f) forView:view];
}


/**
 输入框开始编辑（代理方法）
 
 @param textField 输入框
 */
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    
    /* 改变线的颜色 */
    if (textField == self.telePhoneTextField) {
        
        self.telePhoneIsEdit = YES;
        self.codeIsEdit = NO;
        self.telePhoneLabel.textColor = [UIColor whiteColor];
    }
    else if (textField == self.codeTextField) {
        
        self.telePhoneIsEdit = NO;
        self.codeIsEdit = YES;
        self.codeLabel.textColor = [UIColor whiteColor];
    }
}


/**
 输入框结束编辑（代理方法）
 
 @param textField 输入框
 */
- (void)textFieldDidEndEditing:(UITextField *)textField {
    
    /* 开始标题还原的动画效果 */
    if (textField.text.length == 0) {
        
        [self startLabelAnimation:NO];
        /* 改变线的颜色 */
        if (textField == self.telePhoneTextField) {

            self.telePhoneLabel.textColor = [UIColor colorWithHex:0x99999];
            self.telePhoneLine.path = [self getBezierLine1:self.codeTextField.frame.size.width];
        }
        else if (textField == self.codeTextField) {

            self.codeLabel.textColor = [UIColor colorWithHex:0x99999];
            self.codeLine.path = [self getBezierLine1:self.codeTextField.frame.size.width];
        }
     /* 改变线的颜色 */
    }else if (textField == self.telePhoneTextField) {
        
        self.telePhoneLine.path = [self getBezierPath:lineNormalControlY];
    }
    else if (textField == self.codeTextField) {
        
        self.codeLine.path = [self getBezierPath:lineNormalControlY];
    }

        
    
}

/**
 点击空白结束编辑
 */
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [self.view endEditing:YES];
}


/**
 *  键盘弹出
 */
- (void)keyboardWillShow:(NSNotification *)aNotification {
    
    /* 获取键盘的高度 */
    NSDictionary *userInfo = aNotification.userInfo;
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = aValue.CGRectValue;
    
    /* 输入框上移 */
    CGFloat padding = 20;
    CGRect frame = self.loginButton.frame;
    CGFloat height = self.view.frame.size.height - frame.origin.y - frame.size.height;
    if (height < keyboardRect.size.height + padding) {
        
        [UIView animateWithDuration:normalAnimationDuration animations:^ {
            
            CGRect frame = self.view.frame;
            frame.origin.y = -(keyboardRect.size.height - height + padding);
            self.view.frame = frame;
        }];
    }
}


/**
 *  键盘退出
 */
- (void)keyboardWillHide:(NSNotification *)aNotification {
    
    /* 输入框下移 */
    [UIView animateWithDuration:normalAnimationDuration animations:^ {
        
        CGRect frame = self.view.frame;
        frame.origin.y = 0;
        self.view.frame = frame;
    }];
}



- (void)bindViewModel
{
    [super bindViewModel];
    
    //绑定数据
    RAC(self.viewModel, telePhoneStr) = self.telePhoneTextField.rac_textSignal;
    RAC(self.viewModel, codeStr) = self.codeTextField.rac_textSignal;
//    self.viewModel.isTick = self.isTick;
    @weakify(self);
    
    //判断登录按钮是否可以用
    RAC(self.loginButton, enabled) = self.viewModel.validLoginSignal;
    
    [self.viewModel.validLoginSignal
     subscribeNext:^(NSNumber * usernameIsValid) {
         @strongify(self);
         if(usernameIsValid.boolValue){
             [self.loginButton setBackgroundColor:[UIColor colorWithHex:0xffffff alpha:1.0]];
             [self.loginButton setTitleColor:[UIColor colorWithHex:0x42C9C7] forState:UIControlStateNormal];
         }else{
             [self.loginButton setBackgroundColor:[UIColor colorWithHex:0xffffff alpha:0.4]];
             [self.loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
         }
     }];
    //验证码是否可用
    RAC(self.getCodeButton.titleLabel,text) = RACObserve(self.viewModel,phoneCodeText);
    RAC(self.getCodeButton, enabled) = self.viewModel.getCodeSignal;
    
    [[self.codeTextField.rac_keyboardReturnSignal filter:^BOOL(id value) {
        @strongify(self)
        return self.loginButton.enabled;
    }] subscribeNext:^(id x) {
        @strongify(self)
        [self.viewModel.loginCommand execute:nil];
    }];
    //点击获取验证码动作
    [[self.getCodeButton
      rac_signalForControlEvents:UIControlEventTouchUpInside]
     subscribeNext:^(id x) {
         @strongify(self)
         self.codeLine.path = [self getBezierLine1:self.codeTextField.frame.size.width];
         [self startLineAnimation2];
         [self.viewModel.phoneCodeCommand execute:nil];
     }];
    
    //点击登录动作
    [[self.loginButton
      rac_signalForControlEvents:UIControlEventTouchUpInside]
     subscribeNext:^(id x) {
         @strongify(self)
         [self.viewModel.loginCommand execute:nil];
         [self addUserBehaviourString:@"Event_Login"];
//         NSLog(@"登录");
//         
//         AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//         
//         manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
//         
//         NSMutableDictionary *parameters = [NSMutableDictionary new];
//         //    [params setObjectNotNull:[NSUserDefaults arcObjectForKey:APP_DeviceToken_Key] forKey:@"deviceToken"];
//         [parameters setObjectNotNull:[NSUserDefaults arcObjectForKey:APP_GetuiToken_Key] forKey:@"clientId"];
//         [parameters setObjectNotNull:self.telePhoneTextField.text forKey:@"mobile"];
//         [parameters setObjectNotNull:self.codeTextField.text forKey:@"code"];
//         
//         [manager POST:@"http://10.0.16.233/webapp/rest/index.php?c=iuser&a=loginOrRegister"parameters:parameters
//          
//               success:^(AFHTTPRequestOperation *operation,id responseObject)
//          {
//              
//              NSLog(@"Success: %@", operation.responseString);
//              
//          }failure:^(AFHTTPRequestOperation *operation,NSError *error)
//          {
//              
//              NSLog(@"Error: %@", error);
//              
//          }];
         
     }];
    
    [[self.userAgreement rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        @strongify(self);
        [self.viewModel.userAgreement execute:nil];
//        self.viewModel.
    }];
    
}



#pragma mark --

- (PreLoginViewModel*)viewModel{
    if (!_viewModel) {
        _viewModel = [[PreLoginViewModel alloc] initWithViewController:self];
    }
    return _viewModel;
}

@end
